﻿
using System.Collections.Generic;
using PEProtocol;
using UnityEngine;

/**
 * 战场的管理器
 */

public class BattleMgr : MonoBehaviour{
    private ResSvc resSvc;
    private AudioSvc audioSvc;
    private StateMgr stateMgr;
    private SkillMgr skillMgr;
    private MapMgr mapMgr;

    private MapCfg mapCfg;

    private EntityPlayer entitySelfPlayer;

    private Dictionary<string, EntityBase> monsterDic = new Dictionary<string, EntityBase>();

    public void Init(int mapid){
        resSvc = ResSvc.Instance;
        audioSvc = AudioSvc.Instance;

        //初始化各个管理器
        stateMgr = gameObject.AddComponent<StateMgr>();
        stateMgr.Init();
        skillMgr = gameObject.AddComponent<SkillMgr>();
        skillMgr.Init();
        
        //加载战斗地图
        mapCfg = resSvc.GetMapCfgData(mapid);
        resSvc.AsyncLoadScene(mapCfg.sceneName, () => {
            //初始化地图数据
            GameObject map = GameObject.FindGameObjectWithTag("MapRoot");
            mapMgr = map.GetComponent<MapMgr>();
            mapMgr.Init(this);
            
            map.transform.localPosition = Vector3.zero;
            map.transform.localScale = Vector3.one;

            Camera.main.transform.position = mapCfg.mainCamPos;
            Camera.main.transform.localEulerAngles = mapCfg.mainCamRote;
            
            LoadPlayer(mapCfg);
            entitySelfPlayer.Idle();
            BattleSys.Instance.SetPlayerCtlWndState();
            
            //激活第一批次怪物
            ActiveCurrentBatchMonsters();

            audioSvc.PlayBGMusic(Constants.BGHuangYe);
        });

    }

    private void LoadPlayer(MapCfg mapData){
        GameObject player = resSvc.LoadPrefab(PathDefine.AssissnBattlePlayerPrefab);

        player.transform.position = mapData.playerBornPos;
        player.transform.localEulerAngles = mapData.playerBornRote;
        player.transform.localScale = Vector3.one;

        entitySelfPlayer = new EntityPlayer();
        entitySelfPlayer.stateMgr = stateMgr;
        entitySelfPlayer.skillMgr = skillMgr;
        entitySelfPlayer.battleMgr = this;

        PlayerData pd = GameRoot.Instance.PlayerData;
        entitySelfPlayer.SetBattleProps(
            new BattleProps{
                hp = pd.hp,
                ad = pd.ad,
                ap = pd.ap,
                addef = pd.addef,
                apdef = pd.apdef,
                dodge = pd.dodge,
                pierce = pd.pierce,
                critical = pd.critcal
            }
        );
        entitySelfPlayer.Name = "yunni";
        PlayerController playerCtl = player.GetComponent<PlayerController>();
        playerCtl.Init();
        entitySelfPlayer.SetCtl(playerCtl);
    }

    public void LoadMonsterByWave(int wave){
        for (int i = 0; i < mapCfg.monsterLst.Count; i++){
            MonsterData md = mapCfg.monsterLst[i];
            if (md.mWava == wave){
                GameObject m = resSvc.LoadPrefab(md.mCfg.resPath, true);
                m.transform.localPosition = md.mBornPos;
                m.transform.eulerAngles = md.mBornRote;
                m.transform.localScale = Vector3.one;

                m.name = "m" + md.mWava + "_" + md.mIndex;

                EntityMonster entityMonster = new EntityMonster();
                entityMonster.stateMgr = stateMgr;
                entityMonster.skillMgr = skillMgr;
                entityMonster.battleMgr = this;
                
                //设置初始属性
                entityMonster.md = md;
                entityMonster.SetBattleProps(md.mCfg.bps);

                MonsterController mc = m.GetComponent<MonsterController>();
                mc.Init();
                entityMonster.SetCtl(mc);
                entityMonster.Name = mc.name;
                
                m.SetActive(false);

                monsterDic.Add(m.name, entityMonster);
                
                GameRoot.Instance.dynamicWnd.AddHPItemInfo(mc.name, mc.hpRoot, entityMonster.Hp);
            }
        }
    }

    public void ActiveCurrentBatchMonsters(){
        TimerSvc.Instance.AddTimerTask((int tid) => {
            foreach (KeyValuePair<string,EntityBase> pair in monsterDic){
                pair.Value.SetActive(true);
                pair.Value.Born();
                TimerSvc.Instance.AddTimerTask((int id) => {
                    //出生1秒钟以后进入idle
                    pair.Value.Idle();
                }, 1000);
            }
        }, 500);
    }

    public List<EntityBase> GetEntityMonsters(){
        List<EntityBase> monsters = new List<EntityBase>();
        foreach (KeyValuePair<string,EntityBase> item in monsterDic){
            monsters.Add(item.Value);
        }
        return monsters;
    }

    #region 技能释放与角色控制

    public void SetSelfPlayerMoveDir(Vector2 dir){
        //设置玩家移动
        //PECommon.Log(dir.ToString());
        if (entitySelfPlayer.canControl == false){
            return;
        }
        
        if (dir == Vector2.zero){
            entitySelfPlayer.Idle();
        }
        else{
            entitySelfPlayer.Move();
            entitySelfPlayer.SetDir(dir);
        }
    }

    public void ReqReleaseSkill(int index){
        switch (index){
            case 0:
                ReleaseNormalAtk();
                break;
            case 1:
                ReleaseSkill1();
                break;
            case 2:
                ReleaseSkill2();
                break;
            case 3:
                ReleaseSkill3();
                break;
        }
    }

    private int[] comboArr = new[]{111, 112, 113, 114, 115};
    public int comboIndex = 0;
    public double lastAtkTime = 0;
    private void ReleaseNormalAtk(){
        //PECommon.Log("Click NormalAtk");
        if (entitySelfPlayer.currentAnimState == AniState.Attack){
            //在500ms以内进行第二次点击，存数据
            double nowAtkTime = TimerSvc.Instance.GetNowTime();
            if (nowAtkTime - lastAtkTime < Constants.ComboSpace && lastAtkTime != 0){
                if (comboArr[comboIndex] != comboArr[comboArr.Length - 1]){
                    comboIndex += 1;
                    entitySelfPlayer.comboQue.Enqueue(comboArr[comboIndex]);
                    lastAtkTime = nowAtkTime;
                }
                else{
                    lastAtkTime = 0;
                    comboIndex = 0;
                }
            }
        }
        else if (entitySelfPlayer.currentAnimState == AniState.Idle || entitySelfPlayer.currentAnimState == AniState.Move){
            comboIndex = 0;
            lastAtkTime = TimerSvc.Instance.GetNowTime();
            entitySelfPlayer.Attack(comboArr[comboIndex]);
        }
    }

    private void ReleaseSkill1(){
        //PECommon.Log("Click Skill1");
        entitySelfPlayer.Attack(101);
    }
    
    private void ReleaseSkill2(){
        //PECommon.Log("Click Skill2");
        entitySelfPlayer.Attack(102);
    }
    
    private void ReleaseSkill3(){
        //PECommon.Log("Click Skill3");
        entitySelfPlayer.Attack(103);
    }

    public Vector2 GetDirInput(){
        return BattleSys.Instance.GetDirInput();
    }
    
    #endregion

    public void RemoveMonster(string key){
        EntityBase monster = null;
        if (monsterDic.TryGetValue(key, out monster)){
            monsterDic.Remove(key);
            GameRoot.Instance.dynamicWnd.DelHPItemInfo(key);
        }
    }
}
